<template>
    <el-dialog title="坐标拾取"  v-model="opens" width="60vw" append-to-body destroy-on-close draggable>
        <div class="top-search ">
            <el-form>
                <el-row class="inline-row">
                    <el-col :span="8">
                        <el-form-item label="地址:">
                            <el-input id="addressInfo" v-model="address" placeholder="输地址获取经纬度或者点击地图" @change="changeAdress"
                                class="ht-input" ref="inputRef"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-button slot="append" size="large" type="primary" :icon="Search" @click="onhandelSearch"
                            class="standard-btn">搜索
                        </el-button>
                    </el-col>
                </el-row>
                <el-row class="inline-row">
                    <el-col :span="8">
                        <el-form-item label="经度:">
                            <el-input v-model="location.lng" class="ht-input"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="经度:">
                            <el-input v-model="location.lat" class="ht-input"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div id="container"></div>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="handleDrawStation" class="standard-btn">确 定</el-button>
                <el-button @click="opens = false" class="simple-btn">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup lang="ts" name="MyMap">
import AMapLoader from '@amap/amap-jsapi-loader';
import { shallowRef } from 'vue';
import { onMounted, ref, reactive } from 'vue';
import { Search } from "@element-plus/icons-vue"
const emit = defineEmits(['getLolaAddress']);
const proxy = getCurrentInstance()?.proxy;
const address = ref(null);
const inputRef = ref(null)
const map = shallowRef(null);
const AMaps = shallowRef(null);
const POI = ref(null);
const Geocoder = ref(null);//逆地理编码
const placeSearch = ref(null);
const location = reactive({
    lng: "",
    lat: ""
});
const opens = ref(false);
const marker = ref(null);
const initMap = () => {
    AMapLoader.load({
        key: "53595b6502e504c03360cd51995674cc",
        // key: "747d52d58df816dbc80aa26ef7c1f333",             // 申请好的Web端开发者Key，首次调用 load 时必填
        // key: "9ef40c00bc22241a5a0c073d67cca78e",             // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Scale', 'AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geocoder'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    }).then((AMap) => {
        AMaps.value = AMap;
        map.value = new AMap.Map("container", {  //设置地图容器id
            viewMode: "3D",    //是否为3D地图模式
            zoom: 10,           //初始化地图级别
            // center: [116.397428, 39.90923], //初始化地图中心点位置
        });

        // 地图控件
        map.value.addControl(new AMap.Scale())
        // 搜索框自动完成类
        POI.value = new AMap.AutoComplete({
            input: inputRef.value
        })
        //选中某条记录时触发
        POI.value.on("select", choice)
        //构造地点查询类
        placeSearch.value = new AMap.PlaceSearch({
            map: map.value
        })
        // 地图点击事件
        map.value.on('click', clickMapHandler)
        // poi覆盖物点击事件
        placeSearch.value.on("markerClick", clickMarkerHandler)

        //逆地理编码
        Geocoder.value = new AMap.Geocoder({
            radius: 1000 //范围，默认：500
        });
        // console.log("Amap", AMap)
    }).catch(e => {
        console.log(e);
    })
}
// //地址改变
const changeAdress = (e: any) => {
    console.log("e", e)
}
const onhandelSearch = () => {
    try {
        Geocoder.value.getLocation(address.value, (status, result) => {
            console.log("status", status);
            console.log("result", result)
            if (status === 'complete' && result.geocodes.length) {
                var lnglat = result.geocodes[0].location
                location.lng = lnglat.lng;
                location.lat = lnglat.lat;
                addMarker(lnglat.lng, lnglat.lat)
            } else {
                alert("根据地址查询位置失败");
                proxy.$modal.msgError("根据地址查询位置失败");
            }
        })
    } catch (e) {
        proxy.$modal.msgError("根据地址查询位置失败");
        console.log("e", e)
    }
}
const choice = (e: any) => {
    console.log("e", e)
    console.log(placeSearch.value)
    placeSearch.value.setCity(e.poi.adcode, () => {

    })
    placeSearch.value.search(e.poi.name, (status, result) => {
        console.log("status", status);
        console.log("result", result)
    }) //关键字查询查询
}
const handleDrawStation = () => {
    opens.value = false;
    emit('getLolaAddress', { ...location, address: address.value })
}
//地图点击事件
const clickMapHandler = (e: any) => {
    location.lng = e.lnglat.getLng();
    location.lat = e.lnglat.getLat();
    console.log("e", e)
    addMarker(location.lng, location.lat);
}
// 点击poi覆盖物事件 
const clickMarkerHandler = (e: any) => {
    location.lng = e.data.location.lng
    location.lat = e.data.location.lat
}
//添加覆盖物
const addMarker = (lng: any, lat: any) => {
    if (marker.value !== null) {
        map.value.remove(marker.value);
    }
    marker.value = new AMaps.value.Marker({
        position: new AMaps.value.LngLat(lng, lat),
        offset: new AMaps.value.Pixel(-10, -10),
        title: ''
    });
    map.value.add(marker.value);
    map.value.setFitView();
    Geocoder.value.getAddress([lng, lat], (status, result) => {
        console.log("status", status);
        console.log("result", result)
        if (status === 'complete' && result.regeocode) {
            let formattedAddress = result.regeocode.formattedAddress;
            // address.value = formattedAddress;
            console.log("address", address)
        } else {
            console.log('根据经纬度查询地址失败')
        }
    })
}
const open = (addressName,lng,lat) => {
    address.value = addressName ?? '';
    location.lng =lng ?? '';
    location.lat = lat ?? '';
    opens.value = true;
    initMap()
    if(lng && lat){
        setTimeout(()=>{
            addMarker(lng,lat)
        },1500)
    }
}
onMounted(() => {
    // initMap()
})

//暴露方法给外部使用
defineExpose({
    open
});
</script>
<styles  lang="scss">
#container {
    padding: 0px;
    margin: 0px;
    width: 100%;
    height: 400px;
}

.top-search {
    width: 100%;
    margin: auto;
    z-index: 1;
    position: relative;
    // display: flex;
    // justify-content: space-between;
}

.right-show {
    display: flex;
    width: 100%;
}
</styles>